import laydate from 'laydate-es6';
import ajax from '../utils/ajax';
import upload from '../utils/upload';


const form = document.forms.userinfo;
// console.log(form);
const avatar = document.getElementById('avatar');

init()
function init() {
    // 初始化日历
    init_laydate();
    //默认数据填充到表单
    reset();
    // 增加表单提交事件
    form.onsubmit = form_submit;
    // 上传图片的本地预览
    form.avatar.onchange = avatar_change;
}

function init_laydate() {
    laydate.render({
        elem: "#birthday",
        max: '2023-1-5'
    })
}

async function reset() {
    const { data } = await ajax('get', '/api/getUserInfo');
    console.log(data);
    if (data.nickname) {
        form.nickname.value = data.nickname;
    }
    if (data.gender) {
        form.gender.value = data.gender.data[0] == 0 ? 'male' : 'female';
    }
    if (data.birthday) {
        form.birthday.value = data.birthday.slice(0, 10);
    }
    if (data.avatar) {
        avatar.src = 'http://127.0.0.1:3000' + data.avatar;
    }

}

function form_submit(e) {
    e.preventDefault();
    // 收集表单数据，以formData的形式
    const fd = new FormData(form);
    // 发送请求
    upload('/api/updateUserInfo', fd).then(result => {
        alert(result.msg)
    })
}


// 图片本地预览
function avatar_change() {
    const that = this;
    // 判断文件域有没有选择文件
    if (that.files.length > 0) {
        // 限定文件是图片
        if (!/^image\//.test(that.files[0].type)) {
            alert('请选择图片文件');
            that.value = null;
            avatar.src = '';
            return;
        }
        // 限定文件尺寸
        if (that.files[0].size > 1024 * 200) {
            alert('图片大小不能超过200kB');
            that.value = null;
            avatar.src = '';
            return;
        }
        avatar.src = URL.createObjectURL(that.files[0]);
    } else {
        avatar.src = '';
    }
}
